import SideDrawer from "@/components/CommonComponents/drawer";
import { Input, message, Select } from "antd";
import { Fragment, useEffect, useState } from "react";
import styles from "./index.less";
import cn from "classnames";
import { DRAWER_TITLE } from ".";
import TextEditor from "@/components/TinyEditor";
import icon_checkbox from "@/assets/icons/icon-checkbox.png";
import icon_unCheckbox from "@/assets/icons/icon-unCheckbox.png";
import icon_checkbox_required from "@/assets/icons/icon_checkbox_required.png";
import {
  getMaxReport,
  queryMonetaryAddOptions,
  queryMonetaryReportSigTable,
  saveMacrography,
  saveMonetaryReport,
  saveSellerIncom,
  validateBroker,
  validateMacroBroker,
} from "./service";
import MonetaryEditorText from "./monetaryEditor";
import { transferToText } from "@/utils/utils";

interface EditEventStrategyProps {
  title: string;
  toggleDrawer: (b: boolean, type?: string) => void;
  visible: boolean;
  handleQuery: () => void;
}

interface EditTextProps {
  editType: string;
  editTitle: string;
  callback: (type: string, val: string) => void;
  editContent?: string;
  height: number;
  hasSider?: boolean;
  checkFlag?: string;
  broker?: string;
  isSubmit?: boolean; // 多空判断必填判断
}

const EditText = (props: EditTextProps) => {
  const [hideCheckbox, setHideCheckbox] = useState(true); // 判断失焦隐藏选择框
  const [time, setTime] = useState(Date.now());
  const {
    editTitle,
    editType,
    editContent,
    callback,
    height,
    hasSider,
    checkFlag,
    isSubmit,
  } = props;

  // 失焦判断
  const handleOnBlur = (content: string) => {
    if (hasSider) {
      setTime(Date.now());
    }
    // console.log(content);
    if (!content) {
      setHideCheckbox(true);
      callback(editType.indexOf("Short") > 0 ? "shortFlag" : "middleFlag", "");
    }
  };

  useEffect(() => {
    if (hasSider) {
      if (transferToText(editContent)?.trim()) {
        setHideCheckbox(false);
      }
    }
  }, [editContent, hasSider]);

  // console.log(hideCheckbox, editContent)
  return (
    <div className={styles.editText}>
      <div className={styles.editTextHeader}>
        <span className={cn(styles.editTextHeader_left)}>{editTitle}</span>
        <div className={styles.editTextHeader_right}>
          {/* 0 多 1空 */}
          {hasSider && !hideCheckbox && (
            <Fragment>
              <span className={styles.required} style={{fontWeight: 600, opacity: 0.7}}>多空判断方向(短)</span>
              <div>
                <img
                  src={
                    checkFlag === "0"
                      ? icon_checkbox
                      : isSubmit && !checkFlag
                      ? icon_checkbox_required
                      : icon_unCheckbox
                  }
                  alt="checked"
                  onClick={() =>
                    callback(
                      editType.indexOf("Short") > 0
                        ? "shortFlag"
                        : "middleFlag",
                      checkFlag === "0" ? "" : "0"
                    )
                  }
                />
                <span>多</span>
              </div>
              <div>
                <img
                  src={
                    checkFlag === "1"
                      ? icon_checkbox
                      : isSubmit && !checkFlag
                      ? icon_checkbox_required
                      : icon_unCheckbox
                  }
                  alt="checked"
                  onClick={() =>
                    callback(
                      editType.indexOf("Short") > 0
                        ? "shortFlag"
                        : "middleFlag",
                      checkFlag === "1" ? "" : "1"
                    )
                  }
                />
                <span>空</span>
              </div>
            </Fragment>
          )}
        </div>
      </div>
      {/* {console.log(isSubmit, checkFlag, hasSider, editContent)} */}
      <TextEditor
        editorKey={editType}
        content={editContent}
        onContentChange={(e) => {
          callback(editType, e);
        }}
        onChangePureText={(e) => {
          callback(editType + "Str", e);
        }}
        height={height}
        simToolBar={"bold italic underline forecolor"}
        // isError={isSubmit && checkFlag && hasSider && !editContent}
        onEditorBlur={handleOnBlur}
        paste_as_text={true}
      />
    </div>
  );
};

const EditEventStrategy = (props: EditEventStrategyProps) => {
  const { title, toggleDrawer, visible, handleQuery } = props;
  const [saveParams, setSaveParams] = useState(
    {} as { [propName: string]: string }
  );
  const [errorList, setErrorList] = useState<string[]>([]);
  const [showErrorMsg, setShowErrorMsg] = useState(false);
  const [isSubmit, setIsSubmit] = useState(false);

  const [monetaryAddOptions, setMonetaryAddOptions] = useState([]);
  const [selectMonetaryOption, setSelectMonetaryOption] = useState("");
  // 收集编辑的类别数据
  const [monetaryReportData, setMonetaryReportData] = useState([]); // 一级数据
  const [monetarySecReportData, setMonetarySecReportData] = useState({}); // 已一级name作为key来保存对应的二级数据
  const [repeatFirName, setRepeatFirName] = useState([]); // 重复的一级名称
  const [repeatSecName, setRepeatSecName] = useState({}); // 重复的二级名称
  const [requiredFir, setRequiredFir] = useState([]);

  const [visibleDeleteModal, setVisibleDeleteModal] = useState(false);

  useEffect(() => {
    if (!visible) {
      setSaveParams({});
      setIsSubmit(false);
      setErrorList([]);
      setShowErrorMsg(false);
      setMonetaryReportData([]);
      setMonetarySecReportData({});
      setSelectMonetaryOption("");
      setRepeatFirName([]);
      setRepeatSecName({});
      setRequiredFir([]);
    } else if (visible && props.id) {
      // 编辑
      setSaveParams({ ...props, originalBroker: props.broker });
    }
  }, [visible]);

  useEffect(() => {
    if (title === "3" && visible) {
      const firArr = [];
      const secObj = {};
      const resolveData = (data) => {
        data?.forEach((v) => {
          const i = firArr.findIndex(
            (m) => m.oneLevelCategory === v.oneLevelCategory
          );
          if (i > -1) {
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            console.log(firArr[i].key, secObj[firArr[i].key].length);

            secObj[firArr[i].key].push({
              content: v.content,
              contentStr: v.contentStr,
              id: v.id,
              key: firArr[i].key + "_" + secObj[firArr[i].key].length,
              oneLevelCategory: v.oneLevelCategory,
              reportDate: v.reportDate,
              twoLevelCategory: v.twoLevelCategory,
            });
          } else {
            secObj[firArr.length + ""] = [
              {
                content: v.content,
                contentStr: v.contentStr,
                id: v.id,
                key: firArr.length + "_" + 0,
                oneLevelCategory: v.oneLevelCategory,
                reportDate: v.reportDate,
                twoLevelCategory: v.twoLevelCategory,
              },
            ];
            firArr.push({
              oneLevelCategory: v.oneLevelCategory,
              key: firArr.length + "",
            });
          }
        });
      };
      queryMonetaryAddOptions().then((res) => {
        console.log(res);
        if (res?.code == 0) {
          setMonetaryAddOptions(
            Object.keys(res?.data).map((v) => {
              return {
                key: v,
                label: v,
              };
            })
          );
        }
      });
      if (!props.reportDate) {
        getMaxReport().then((res) => {
          if (res?.code == 0) {
            resolveData(res?.data);
          }
          setMonetaryReportData(firArr);
          setMonetarySecReportData(secObj);
        });
      } else {
        setSelectMonetaryOption(props.reportDate);
        queryMonetaryReportSigTable({ reportDate: props.reportDate }).then(
          (res) => {
            console.log(res);

            if (res?.code == 0) {
              resolveData(res?.data);
            }
            setMonetaryReportData(firArr);
            setMonetarySecReportData(secObj);
          }
        );
      }
    }
  }, [visible, props.reportDate]);

  /**
   *
   * @param key 字段名称
   * @param val 值
   */
  const handleSaveParams = (key: string, val: string) => {
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val,
      };
    });
  };

  // 保存
  const onOk = () => {
    if (title === "3") {
      console.log(
        monetaryReportData,
        monetarySecReportData,
        selectMonetaryOption
      );
      setIsSubmit(true);
      if (!selectMonetaryOption) return;
      const params = [];
      let firArr = [];
      let secArr = [];
      let repeatFirArr = [];
      let repeatSecObj = {};
      let emptyFir = [];
      monetaryReportData.forEach((v) => {
        if (firArr.includes(v.oneLevelCategory)) {
          // 查找重复的一级类别名称
          repeatFirArr.push(v.oneLevelCategory);
        } else {
          v.oneLevelCategory && firArr.push(v.oneLevelCategory);
        }
        repeatSecObj[v.key] = [];
        secArr = [];
        if (
          monetarySecReportData[v.key] &&
          monetarySecReportData[v.key].length > 0
        ) {
          monetarySecReportData[v.key].forEach((m) => {
            // 查找重复的二级名称
            if (secArr.includes(m.twoLevelCategory)) {
              repeatSecObj[v.key].push(m.twoLevelCategory);
            } else {
              secArr.push(m.twoLevelCategory);
            }
            if (
              (m.twoLevelCategory || m.contentStr || m.content) &&
              !v.oneLevelCategory
            ) {
              // 判断二级填了一级未填
              emptyFir.push(v.key);
            }
            if (v.oneLevelCategory || m.content || m.twoLevelCategory) {
              // 如果一级和二级都没填就不会走到这里
              params.push({
                content: m.content || "",
                contentStr: m.contentStr || "",
                id: m.id,
                oneLevelCategory: v.oneLevelCategory || "",
                reportDate: selectMonetaryOption,
                twoLevelCategory: m.twoLevelCategory,
              });
            }
          });
        } else {
          params.push({
            content: "",
            contentStr: "",
            id: v.id,
            oneLevelCategory: v.oneLevelCategory || "",
            reportDate: selectMonetaryOption,
            twoLevelCategory: "",
          });
        }
      });
      setRequiredFir(emptyFir);

      // console.log(params, repeatFirArr, repeatSecObj, emptyFir);
      let isRepeatSec = false;
      for (let r of Object.keys(repeatSecObj)) {
        if (repeatSecObj[r].length > 0) {
          isRepeatSec = true;
          break;
        }
      }
      setRepeatFirName(repeatFirArr);
      setRepeatSecName(repeatSecObj);
      if (repeatFirArr.length > 0 || isRepeatSec || emptyFir.length > 0) return;
      saveMonetaryReport(params).then((res) => {
        if (res?.code === "0") {
          message.success(res.msg);
          toggleDrawer(false);
          handleQuery();
        } else if (res?.code === "1") {
          message.error(res?.data?.message);
        }
      });
    }

    // 下面是非货币政策的逻辑
    if (title === "3") return;
    setIsSubmit(true);
    if (!saveParams?.broker?.trim()) {
      setErrorList(["broker"]);
      return;
    }
    if (showErrorMsg) return; // 校验券商名称失败
    if (!saveParams.shortFlag && saveParams.moreEmptyShort) return; // 多空短必填判断
    if (!saveParams.middleFlag && saveParams.moreEmptyMiddle) return; // 多空中必填判断

    if (title === "1") {
      // 卖方固收组
      if (saveParams.originalBroker === saveParams.broker) {
        saveParams.originalBroker = "";
      }
      saveSellerIncom(saveParams).then((res) => {
        if (res?.code === "0") {
          message.success(res.msg);
          toggleDrawer(false);
          handleQuery();
        } else if (res?.code === "1") {
          message.error(res?.data?.message);
        }
      });
    } else if (title === "2") {
      // 宏观
      if (saveParams.originalBroker === saveParams.broker) {
        saveParams.originalBroker = "";
      }

      saveMacrography(saveParams).then((res) => {
        if (res?.code === "0") {
          message.success(res.msg);
          toggleDrawer(false);
          handleQuery();
        } else if (res?.code === "1") {
          message.error(res?.data?.message);
        }
      });
    }
  };

  // 校验券商中文名
  const handleValidateBroker = () => {
    if (!saveParams.broker.trim()) return;
    let params = {
      broker: saveParams.broker,
    };
    if (saveParams.id) {
      params.createDate = saveParams.createTime;
      params.originalBroker = saveParams.originalBroker;
    }
    if (title === "1") {
      validateBroker(params).then((res) => {
        if (res?.code == "0") {
          setShowErrorMsg(res?.msg);
        }
      });
    } else if (title === "2") {
      validateMacroBroker(params).then((res) => {
        if (res?.code == "0") {
          setShowErrorMsg(res?.msg);
        }
      });
    }
  };

  // 判断货币政策下是否可以点击提交
  const validateButton = () => {
    let bool = true;
    monetaryReportData.forEach((v) => {
      if (v.oneLevelCategory) {
        bool = false;
      }
    });
    if (!bool) return bool;
    for (let r of Object.keys(monetarySecReportData)) {
      if (!bool) break;
      if (monetarySecReportData[r]) {
        monetarySecReportData[r].forEach((v) => {
          if (v.twoLevelCategory || v.content) {
            bool = false;
          }
        });
      }
    }
    return bool;
  };

  // 判断卖方下是否按钮可点击
  const validateSellerBtn = () => {
    let bool = true;
    console.log(saveParams);
    const list = [
      "convertibleTactics",
      "convertibleTacticsStr",
      "coreContent",
      "coreContentStr",
      "creditTactics",
      "creditTacticsStr",
      "deriveTactics",
      "deriveTacticsStr",
      "moreEmptyMiddle",
      "moreEmptyMiddleStr",
      "moreEmptyShort",
      "moreEmptyShortStr",
      "logic",
      "logicStr",
      "marketContent",
      "marketContentStr",
    ];
    for (let key of list) {
      if (key !== "broker" && transferToText(saveParams[key])?.trim()) {
        bool = false;
        break;
      }
    }
    return bool;
  };

  return (
    <SideDrawer
      title={
        saveParams.id || props.reportDate
          ? DRAWER_TITLE[title]?.replace("新增", "编辑")
          : DRAWER_TITLE[title]
      }
      onClose={() => {
        toggleDrawer(false);
      }}
      visible={visible}
      onOk={onOk}
      contentWrapperStyle={{ width: "95%" }}
      okText="确认"
      disabledLeft={
        (title === "3" && validateButton()) ||
        (title !== "3" && validateSellerBtn())
      }
      cancelText="取消"
      bodyStyle={{
        paddingBottom: 24,
      }}
      mask={visibleDeleteModal ? false : true}
    >
      <div className={styles.headerAdd}>
        {title === "3" ? (
          <div>
            <span className={styles.header_title}>日期</span>
            <Select
              className={[
                styles.select236,
                "findfit_select_autoscroll_x",
                isSubmit && !selectMonetaryOption && "form_error",
              ]}
              // allowClear
              showArrow={true}
              placeholder="请选择"
              disabled={props.reportDate}
              suffixIcon={
                <span
                  className={cn(
                    styles.stock_reporter_arrow,
                    "findfit_icon findfit_icon_arrow "
                  )}
                ></span>
              }
              style={{ marginLeft: -4 }}
              onChange={setSelectMonetaryOption}
              value={selectMonetaryOption}
            >
              {monetaryAddOptions.length > 0 &&
                monetaryAddOptions.map((i: any) => (
                  // eslint-disable-next-line react/jsx-no-undef
                  <Option value={i.key} key={i.key}>
                    {i.label}
                  </Option>
                ))}
            </Select>
          </div>
        ) : (
          <div>
            <span className={styles.header_title}>券商</span>
            <Input
              onChange={(e) => {
                if (e) {
                  setErrorList((state) => {
                    return state.filter((v) => v !== "broker");
                  });
                }
                handleSaveParams("broker", e.target.value);
              }}
              placeholder="请输入"
              className={cn(
                styles.header_titleInput,
                (errorList.includes("broker") || showErrorMsg) && "form_error"
              )}
              maxLength={50}
              style={{ width: 236 }}
              value={saveParams["broker"]}
              onBlur={handleValidateBroker}
              disabled={saveParams.id}
            />
            {showErrorMsg && (
              <span className={styles.errormsg}>{showErrorMsg}</span>
            )}
          </div>
        )}
      </div>
      {title === "1" && (
        <Fragment>
          <EditText
            editType="moreEmptyShort"
            editTitle="多空判断(短)"
            editContent={saveParams["moreEmptyShort"]}
            callback={handleSaveParams}
            checkFlag={saveParams["shortFlag"]}
            height={150}
            hasSider={true}
            isSubmit={isSubmit}
          />
          <EditText
            editType="moreEmptyMiddle"
            editTitle="多空判断(中)"
            editContent={saveParams["moreEmptyMiddle"]}
            callback={handleSaveParams}
            checkFlag={saveParams["middleFlag"]}
            height={150}
            hasSider={true}
            isSubmit={isSubmit}
          />
          <EditText
            editType="coreContent"
            editTitle="核心观点"
            editContent={saveParams["coreContent"]}
            callback={handleSaveParams}
            height={200}
          />
          <EditText
            editType="logic"
            editTitle="分析逻辑"
            editContent={saveParams["logic"]}
            callback={handleSaveParams}
            height={200}
          />
          <EditText
            editType="deriveTactics"
            editTitle="利率/衍生品策略"
            editContent={saveParams["deriveTactics"]}
            callback={handleSaveParams}
            height={150}
          />
          <EditText
            editType="creditTactics"
            editTitle="信用策略"
            editContent={saveParams["creditTactics"]}
            callback={handleSaveParams}
            height={150}
          />
          <EditText
            editType="convertibleTactics"
            editTitle="转债策略"
            editContent={saveParams["convertibleTactics"]}
            callback={handleSaveParams}
            height={150}
          />
        </Fragment>
      )}
      {title === "2" && (
        <Fragment>
          <EditText
            editType="marketContent"
            editTitle="市场观点"
            editContent={saveParams["marketContent"]}
            callback={handleSaveParams}
            height={150}
          />
          <EditText
            editType="logic"
            editTitle="分析逻辑"
            editContent={saveParams["logic"]}
            callback={handleSaveParams}
            height={200}
          />
        </Fragment>
      )}
      {title === "3" && (
        <Fragment>
          <MonetaryEditorText
            monetaryReportData={monetaryReportData}
            monetarySecReportData={monetarySecReportData}
            setMonetaryReportData={setMonetaryReportData}
            setMonetarySecReportData={setMonetarySecReportData}
            repeatFirName={repeatFirName}
            repeatSecName={repeatSecName}
            setRepeatFirName={setRepeatFirName}
            setRepeatSecName={setRepeatSecName}
            requiredFir={requiredFir}
            setRequiredFir={setRequiredFir}
            setVisibleDeleteModal={setVisibleDeleteModal}
          />
        </Fragment>
      )}
    </SideDrawer>
  );
};

export default EditEventStrategy;
